package com.kl.shiro;//package com.kl.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kl.entity.User;
import com.kl.mapper.UserMapper;
import com.kl.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //授权方法
        System.out.println("进入授权方法");
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //认证方法
        //1. 取出账号和 用户名
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//        User user =new User();
//        user.setName(token.getUsername());

//        User user = userService.selectInfo(token.getUsername());

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("name",token.getUsername());
        List<User> list = userMapper.selectList(wrapper);
        User user = list.get(0);


        if (!token.getUsername().equals(user.getName())){
            return null;
        }

        return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSale()),user.getName());
//        return null;
    }
}
